var sid;
$(function() {
	sid = $("#sid").val();
	getActTime();// 该站断路器动作时间
	getActTimeDataForDensity();// 动作时间概率分布
	getArcTimeDataForDensity();// 熄弧时间概率分布
	//该站断路器动作时间
	var t1 = window.setInterval(function() {
		var w = $('#pane2').width() + "";
		if (w != '0') {
			var width = parseInt(w) - 20 + 'px';
			$("#actTimeLine").css("width", width);
			actChart.resize();
			window.clearInterval(t1);
		}
	}, 20);
    //该站断路器动作概率分布
	var t2 = window.setInterval(function() {
        var w = $('#pane3').width() + "";
        if (w != '0') {
        	var width = parseInt(w) - 20 + 'px';
			$("#xihu").css("width", width);
        	if (xihuChart != "" && xihuChart != null && typeof (xihuChart) != undefined) {
        		xihuChart.resize();
		    }
		    window.clearInterval(t2);
		}
    }, 20);
	$('#startTimeAct,#startTimeArc,#startTimeActRate').datetimepicker({
		minView : 2,
		autoclose : true,
		format : 'yyyy-mm-dd'
	});
	$('#endTimeAct,#endTimeArc,#endTimeActRate').datetimepicker({
		minView : 2,
		autoclose : true,
		format : 'yyyy-mm-dd'
	});
});
//熄弧时间--熄弧时间概率分布
$("#tab4").on("click", function() {
	var width = parseInt($('#pane4').css('width')) - 80;	
	$("#arcProperty").css("width", width/2+'px');
	$("#arcPie").css("width", width/2+'px');
	if (arcProperty != "" && arcProperty != null && typeof (arcProperty) != undefined) {
		arcProperty.resize();
    }
	if (arcPie != "" && arcPie != null && typeof (arcPie) != undefined) {
		arcPie.getChart().resize();
    }
});
//动作时间--动作时间概率分布
$("#tab6").on("click",	function() {
    var width = parseInt($('#pane6').css('width')) - 20;
	$("#actPie").css("width", width);
	if (actPie != "" && actPie != null && typeof (actPie) != undefined) {
    	actPie.getChart().resize();
    }
});
$('#check-btnArc').on('click', function() {
	tb.getTable().destroy();
	$("#abnormalArcTime").empty();
	getXiHuTime();
});
$('#check-btnAct').on('click', function() {
	getActTime();
});
$('#check-btn1').on('click', function() {
	getArcTimeDataForDensity();
});
//动作时间概率分布-查询按钮
$('#check-btn2').on('click', function() {
	getActTimeDataForDensity();
});
// 获取组合条件对象
function getArcOption() {
	var option = {
		vol : '',
		type : '',
		manufacturer : '',
		model : '',
		startDate : "",
		endDate : ""
	};
	option.vol = $("#voltage1").val();
	option.type = $("#type1").val();
	// option.startDate = $("#startTime1").val();
	// option.endDate = $("#endTime1").val();
	option.manufacturer = $("#manufacture1").val();
	option.model = $("#model1").val();

	return option;
}
//设置获取熄弧时间概率分布的数据
function getActOption() {
	var option = {
		vol : '',
		type : '',
		manufacturer : '',
		model : '',
		startDate : "",
		endDate : ""
	};
	option.vol = $("#voltage2").val();
	option.type = $("#type2").val();
	option.startDate = $("#startTimeActRate").val();
	option.endDate = $("#endTimeActRate").val();
	option.manufacturer = $("#manufacture2").val();
	option.model = $("#model2").val();

	return option;
}
//初始化加载熄弧时间概率分布
function getArcTimeDataForDensity() {
	var option = getArcOption();
	$.getJSON("/rest/breakerRunSafe/getBreakerActInfosForArc/"
			+ JSON.stringify(option), function(result) {
		var arcData = [];
		for ( var i in result) {
			arcData.push(result[i].xhTimeInterval / 1000);
		}
		initArcDensityChart(arcData);
		getXiHuTime();// 获取该站的熄弧时间
	});
}
function getXiHuTime() {
	var startDate = $("#startTimeArc").val();
	var endDate = $("#endTimeArc").val();
	startDate = (startDate == "") ? null : startDate;
	endDate = (endDate == "") ? null : endDate;
	$.getJSON("/rest/breakerRunSafe/getBreakerArcTimesByStationId/" + startDate
			+ "/" + endDate + "/" + sid, function(result) {
		initArcChart(result);
		var arc = [];
		for ( var name in result) {
			for ( var i in result[name]) {
				arc.push([ name, result[name][i][0], result[name][i][1] ]);
			}
		}
		abnormalArc(arc);
	});
}
// 熄弧时间
var xihu_time = [];
var xihuChart;
function initArcChart(arcTimeMap) {
	if(noData(arcTimeMap,"pane3")){return;}
	var resultData = arcTimeMap;
	var legendName = [];
	var firstXTitle = [];
	var oSeries = [];
	for (var name in resultData){
		legendName.push(name);
		var length = resultData[name].length;
		var title = [];
		if(resultData[name].length>1){
			resultData[name].sort(function(a,b){
				return a[0]> b[0] ? 1 : -1
			});
		}
		
		for(var i=0;i<length;i++){
			resultData[name][i][0] = datefomate(resultData[name][i][0]);
			title[i] = [resultData[name][i][0],resultData[name][i][1]];
		}
		oSeries.push({name:name,data:title,type:'line',barWidth:'30'});
	}
	for(var i=0;i<resultData[legendName[0]].length;i++){
		var data = resultData[legendName[0]][i];
		firstXTitle.push(data[0]);
	}
	xihuChart = echarts.init(document.getElementById('xihu'));
	var opt = {
			legend: {
	            data:legendName,
	            selectedMode : 'single',
	            type:'scroll'
	        },
	        tooltip:{
	        	formatter:function(params) {
	        		return params.data[0] + "<br/>" + params.seriesName + " : " + params.data[1]+ "ms";
	        	}
	        },
	        toolbox:{
	        	feature:{
	        		magicType:{type:['line','bar']},
	        		dataView:{
	        			optionToContent:function(opt) {
	        				var series = opt.series;
	        				var table = '<table border="1" style="width:100%;text-align:center"><tbody><tr>';
	        				for (var j = 0; j < series.length; j++) {
	        					table = table + '<td colspan=2>' + series[j].name+ '</td></tr><tr>';
	        					for (var i = 0, l = series[j].data.length; i < l; i++) {
	        						table += '<td>' + series[j].data[i][0] + '</td><td>'+ series[j].data[i][1] + '</td></tr>';
	        					}
	        				}
	        				table += '</tbody></table>';
	        				return table;
	        			}
	        		}
	        	}
	        },
			xAxis: {
				type: 'category',
			    axisTick: {alignWithLabel: true,},
			    name:"日期",//坐标轴名称。
		        nameLocation:'end',//坐标轴名称显示位置。
		        data:firstXTitle,
			    axisLabel: {
			        // 坐标轴刻度标签的相关设置。
			    	show: true,
			        interval: 0,
			        formatter : function(params){return xAxisTitleWrap(params)},
			    },		        
			},
			yAxis: {
				type: 'value',
			    name: '熄弧时间/ms',
			    nameLocation:'end',
			},
			series:oSeries
	};
	xihuChart.setOption(opt);
	//设置
	xihuChart.on('legendselectchanged', function(obj) {
	    var name=obj.name;
	    var option=xihuChart.getOption();
	    for(var i=0;i<legendName.length;i++){
	    	if(name==legendName[0]){
		        option.xAxis[0].data=firstXTitle;
		    }
		    else{
		    	var data = resultData[legendName[i]]
		    	var showTitle=[];
		    	for(var j=0;j<data.length;j++){
		    		showTitle.push(data[j][0])
		    	}
		        option.xAxis[0].data=showTitle;
		    }
	    }
	    
	    xihuChart.setOption(option,true);
	});
}

// 熄弧时间概率分布
var arcProperty;
var gd1;
function initArcDensityChart(dataSet) {
	gd1 = new GaussianDistribution(dataSet);
	var skewDistribution = new SkewDistribution(dataSet);
	skewDistribution.init();
	var xData=skewDistribution.getXData();
	var yData=skewDistribution.getYData();
	var lineYData=yData.slice(0);
	//lineYData.splice(1,1);
	var option = {
		    xAxis: [{type: 'category',data:xData,name:"熄弧时间(ms)"}],
		    yAxis: {
		    	splitLine: {lineStyle: {color: 'rgba(131,101,101,0.2)',type: 'dashed'}},
		        name:'次数'
		    },
		    tooltip: {
		        trigger: 'axis',
		        axisPointer: {type: 'cross'}
		    },
		    dataZoom: [{type: 'inside'}, {type: 'slider'}],
		    series: [{type: 'bar',data: yData,name: '平均频次'}, 
		    	{data: lineYData,type: 'line',smooth: true,name: '平均频率',showSymbol:false}]
		};
	arcProperty = echarts.init(document.getElementById("arcProperty"));
	arcProperty.setOption(option);
	//设置熄弧时间[熄弧时间概率分布]的饼图
	initArcPieData(dataSet);
	$("#totalNum").html(dataSet.length);
}
//熄弧时间异常分析结果
var tb;
function abnormalArc(arc) {
	var opt = MyTable.getDefaultOptions();
	opt.paging = true;
	opt.searching = true;
	tb = new MyTable('abnormalArcTime', [ '断路器', '故障时间', '熄弧时间' ], opt);
	var abnormalArc = gd1.abnormalAnalyse(arc);
	tb.setDataSet(abnormalArc);
	tb.show();
}

//熄弧时间[熄弧时间概率分布]
var arcPie;
function initArcPieData(arcData) {
	//组装饼图合适的数据
	arcData.sort(function(a,b){
		return a-b;
	});
	var arcPieData = [];
	var lagTimeMap = new Map();
	var max = arcData[arcData.length-1];
	var min = 0;
	var maxValue=0;//所有数值中的最大值
	var gt80Num=0;//大于80的个数
	/*for (var j = min; j <= max; j+=5) {
		var legend = "[" + j + "ms," + (j + 5)  + "ms]";
		arcPieData.push([ legend, 0 ]);
	}*/
	var index=0;
	while(index<=max){
		var legend = "[" +index + "ms," + (index+ 5)  + "ms]";
		arcPieData.push([ legend, 0 ]);
		index+=5;
	}
	
	for(var i in arcData){
		var t = Number(arcData[i]);
		var index=Math.floor(t/5);
		if(t>maxValue){
			maxValue=t;
		}
		if(t>max){
			gt80Num++;
		}else{
			arcPieData[index][1]++;
		}
	}
	if(gt80Num>0){
		var legend = "["+max+"ms," + maxValue + "ms]";
		arcPieData.push([legend,gt80Num]);
	}
	//用数据组装饼图
	arcPie = new Pie("arcPie");
	arcPie.setPie(arcPieData).setPieCenter('50%', '55%')
	  .setPieOuterRadius("50%").setPieLabelFormatter("{d}%");
	var opt = arcPie.getOption();
	opt.legend.top = 30;
	arcPie.show();
}
// 动作时间
var actChart;
function getActTime() {
	var startDate = $("#startTimeAct").val() == "" ? null : $("#startTimeAct").val();
	var endDate = $("#endTimeAct").val() == "" ? null : $("#endTimeAct").val();
	$.getJSON("/rest/breakerRunSafe/getBreakerActTimesByStationId/" + startDate+ "/" + endDate + "/" + sid, function(result) {
		initActChart(result);
		$("#loading").hide();
	});
}
function initActChart(act_time) {
	var resultData = act_time;
	if(noData(resultData,"pane5")){return;}
	var legendName = [];
	var firstXTitle = [];
	var oSeries = [];
	for (var name in resultData){
		legendName.push(name);
		var length = resultData[name].length;
		var title = [];
		if(resultData[name].length>1){
			resultData[name].sort(function(a,b){
				return a[0]> b[0] ? 1 : -1
			});
		}
		
		for(var i=0;i<length;i++){
			resultData[name][i][0] = datefomate(resultData[name][i][0]);
			title[i] = [resultData[name][i][0],resultData[name][i][1]];
		}
		oSeries.push({name:name,data:title,type:'line',barWidth:'30'});
	}
	for(var i=0;i<resultData[legendName[0]].length;i++){
		var data = resultData[legendName[0]][i];
		firstXTitle.push(data[0]);
	}
	actChart = echarts.init(document.getElementById('actTimeLine'));
	
	var opt = {
			legend: {
	            data:legendName,
	            selectedMode : 'single',
	            type:'scroll'
	        },
	        tooltip:{
	        	formatter:function(params) {
	        		return params.data[0] + "<br/>" + params.seriesName + " : " + params.data[1]+ "ms";
	        	}
	        },
	        toolbox:{
	        	feature:{
	        		magicType:{type:['line','bar']},
	        		dataView:{
	        			optionToContent:function(opt) {
	        				var series = opt.series;
	        				var table = '<table border="1" style="width:100%;text-align:center"><tbody><tr>';
	        				for (var j = 0; j < series.length; j++) {
	        					table = table + '<td colspan=2>' + series[j].name+ '</td></tr><tr>';
	        					for (var i = 0, l = series[j].data.length; i < l; i++) {
	        						table += '<td>' + series[j].data[i][0] + '</td><td>'+ series[j].data[i][1] + '</td></tr>';
	        					}
	        				}
	        				table += '</tbody></table>';
	        				return table;
	        			}
	        		}
	        	}
	        },
			xAxis: {
				type: 'category',
			    axisTick: {alignWithLabel: true,},
			    name:"日期",//坐标轴名称。
		        nameLocation:'end',//坐标轴名称显示位置。
		        data:firstXTitle,
			    axisLabel: {
			        // 坐标轴刻度标签的相关设置。
			    	show: true,
			        interval: 0,
			        formatter : function(params){return xAxisTitleWrap(params)},
			    },		        
			},
			yAxis: {
				type: 'value',
			    name: '动作时间/ms',
			    nameLocation:'end',
			},
			series:oSeries
	};
	actChart.setOption(opt);
	//设置
	actChart.on('legendselectchanged', function(obj) {
	    var name=obj.name;
	    var option=actChart.getOption();
	    for(var i=0;i<legendName.length;i++){
	    	if(name==legendName[0]){
		        option.xAxis[0].data=firstXTitle;
		    }
		    else{
		    	var data = resultData[legendName[i]]
		    	var showTitle=[];
		    	for(var j=0;j<data.length;j++){
		    		showTitle.push(data[j][0])
		    	}
		        option.xAxis[0].data=showTitle;
		    }
	    }
	    
	    actChart.setOption(option,true);
	});
}

// 断路器动作时间概率分布
var actProperty;
var actPie;
var actData = [];
function getActTimeDataForDensity() {
	var option = getActOption();
	$.getJSON('/rest/breakerRunSafe/getBreakerActInfos/'+ JSON.stringify(option), function(result) {
		for ( var i in result) {
			actData.push(result[i].distance0MomentsTime / 1000);
		}
		initActPieData(result);
		//initActDensityChart(result);
	});
}
function initActDensityChart(result) {
	actProperty = new Category2YLine("actProperty");
	// 概率分布
	var gd2 = new GaussianDistribution(actData);
	var obj = gd2.getXData();
	// 动作时间
	var act_avg_time = obj.xData;
	var frequency = obj.xNum;
	var yData = gd2.proDensity(act_avg_time);
	actProperty.setxAxis(act_avg_time);
	actProperty.sety1Axis(frequency);
	actProperty.setyAxisName('频率');
	for ( var i in yData) {
		yData[i] = yData[i].toFixed(2);
	}
	actProperty.sety2Axis(yData);
	actProperty.setyAxisName('概率密度');
	var opt = actProperty.getOption();
	opt.series[0].type = 'bar';
	opt.series[1].smooth = true;
	opt.series[1].areaStyle.normal.opacity = 0;
	opt.series[1].showSymbol = false;
	actProperty.show();
	//initActPieData();
}
// 动作时间概率分布
function initActPieData(actPieData) {
	actPieData = [];
	var lagTimeMap = new Map();
	var max = 80;
	var min = 0;
	var maxValue = 0;// 所有数值中的最大值
	var gt80Num = 0;// 大于80的个数
	for ( var i in actData) {
		var t = Number(actData[i]);
		var m = t % 10;
		if (t > maxValue) {
			maxValue = t;
		}
		if (t > max) {
			gt80Num++;
		} else {
			var num = lagTimeMap.get(m);
			if (!num) {
				num = 0;
			}
			num++;
			lagTimeMap.put(m, num);
		}
	}
	for (var j = Math.floor(min / 10); j < max / 10; j++) {
		var legend = "[" + j * 10 + "ms," + (j + 1) * 10 + "ms]";
		var num = lagTimeMap.get(j);
		if (!num) {
			num = 0;
		}
		actPieData.push([ legend, num ]);
	}
	if (gt80Num > 0) {
		var legend = "[" + max + "ms," + maxValue + "ms]";
		actPieData.push([ legend, gt80Num ]);
	}
	initActPie(actPieData);
}
function initActPie(actPieData) {
	actPie = new Pie("actPie");
	actPie.setPie(actPieData).setPieCenter('50%', '55%').setPieOuterRadius(
			"50%").setPieLabelFormatter("{d}%");
	var opt = actPie.getOption();
	opt.legend.top = 30;
	actPie.show();
}
//无数据时的展示
function noData(data,domId){
	var result = false;
	$("#"+domId).removeClass("hideDom");
	if(JSON.stringify(data) == "{}"){
		$("#"+domId).html('<div id="noData" class="noData">暂无数据</div>')
		result = true;
	}
	return result;
}
//x轴名称过长换行显示
function xAxisTitleWrap(params){
    var newParamsName = "";// 最终拼接成的字符串
    var paramsNameNumber = params.length;// 实际标签的个数
    var provideNumber = 10;// 每行能显示的字的个数
    var rowNumber = Math.ceil(paramsNameNumber / provideNumber);// 换行的话，需要显示几行，向上取整
    /* 判断标签的个数是否大于规定的个数， 如果大于，则进行换行处理 如果不大于，即等于或小于，就返回原标签 */
    // 条件等同于rowNumber>1
    if (paramsNameNumber > provideNumber) {
    	/** 循环每一行,p表示行 */
        for (var p = 0; p < rowNumber; p++) {
        	var tempStr = "";// 表示每一次截取的字符串
            var start = p * provideNumber;// 开始截取的位置
            var end = start + provideNumber;// 结束截取的位置
            // 此处特殊处理最后一行的索引值
            if (p == rowNumber - 1) {
             // 最后一次不换行
                 tempStr = params.substring(start, paramsNameNumber);
            } else {
                 // 每一次拼接字符串并换行
                 tempStr = params.substring(start, end) + "\n";
            }
            newParamsName += tempStr;// 最终拼成的字符串
        }

    } else {
    	// 将旧标签的值赋给新标签
        newParamsName = params;
    }
    //将最终的字符串返回
    return newParamsName
}
//处理时间用来删除毫秒
function datefomate(value) {
    if(value==null || value == undefined){
        return "";
    }
    var date = new Date(value); 
    Y = date.getFullYear(),
    M = date.getMonth()+1,
    d = date.getDate(),
    H = date.getHours(),
    m = date.getMinutes(),
    s = date.getSeconds();
    return Y+'-'+M+'-'+d+' '+H+':'+m+':'+s;
};